#!/bin/bash
#该脚本的作用是通过传入的目录，监控该目录的变化，变实时重载服务器，以实现代码热更新的目的,调试时特别有用
#依赖 inotify-tool库 ext目录里有，安装到/usr/local/inotify目录
#用法：inotify /path/to [app_name]
#第二个参数指定只监控哪个应用
#2 inotify list  列出当前监控哪些目录
#3 inotify stop 停止当前监控的所有目录
#4 inotify start 开始 etc 配置目录里的应用

path=$(cd `dirname "$0"`;pwd)
#app根路径
app_root=/home/www

do_start(){
  app_name="$1"
  listen_path=$app_root/$app_name
  last_time=''
  if [ -e "$listen_path" ];then
    /usr/local/inotify/bin/inotifywait -rmq --exclude $listen_path/logs -e modify,create,delete,moved_to $listen_path | while read event;
    do
      ret=`echo $event|grep tmp`
      now=`date +'%s'`
      diff=$[now-last_time]
      if [[ "$ret" = "" ]] && [[ $diff -ge 1 ]];then
        $path/cxsv restart $app_name
        # echo "restart $app_name"
        if [ -e "${path}/etc/${app_name}admin.ini" ];then
          $path/cxsv restart "${app_name}admin"
          # echo "restart ${app_name}admin"
        fi
        if [ -e "${path}/etc/${app_name}user.ini" ];then
          $path/cxsv restart "${app_name}user"
          # echo "restart ${app_name}user"
        fi
      fi
      last_time=`date +'%s'`
    done >> /dev/null &
    echo "Start $app_name ok";
  fi
}


case "$1" in
  start)
    if [ ! -z "$2" ];then
      do_start $2
      exit 0
    else
      for app in $(ls "${path}/etc"|grep -v createConfig|grep -v swoole|awk -F . '{print $1}');do
        if [ -e "${path}/etc/${app}.ini" ];then
          do_start $app;
        fi
      done
    fi
    exit 0;;

  stop)
    if [ ! -z "$2" ];then
      $0 list|grep $2|awk '{print $1}'|xargs kill -9
      echo -e "Stoped $2 ok!"
    else
      ps aux|grep inotify|grep -v grep|awk '{print $2}'|xargs kill -9
      echo -e "Stoped all ok!"
    fi
    exit 0;;

  list)
    ps aux|grep inotifywait|grep -v grep|awk '{print $2" "$17}'
    exit 0;;

    *)
    echo -e "Usega start [app_name] | stop [app_name] | list"
    exit 1;;
esac
exit 0